/**
 * @author Chad Dettmering
 */


package org.flckphoto;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.os.Environment;
import android.util.Log;

/**
 * Holds some settings data for the entire
 * application to use
 */
public class Settings {
	
	private static final String TAG = "Settings";
	
	/**
	 * the name of the settings file
	 */
	public static final String FILENAME = "settings.config";
	
	/**
	 * the absolute datapath for saving pictures
	 * in this application
	 */
	private static final String DATAPATH = File.separator + "DCIM" + File.separator + "FlickPhoto" + File.separator;
	
	/**
	 * the username given to us by the user,
	 * also the current username in settings.config
	 */
	public static String username;
	
	/**
	 * the password given to us by the user,
	 * also the current password in settings.config
	 */
	public static String password;
	
	/**
	 * the authentication token used for authenticated calls to Flickr
	 */
	public static String authToken;
	
	/**
	 * creates the default settings file given the FileOutputStream
	 * @param f the FileOutputStream obtained from openFileOutput(Settings.FILENAME)
	 * @throws IOException, if write fails
	 */
	public static void createDefaultSettings(FileOutputStream f) throws IOException{
		String defaultFile = "placeholder placeholder xxxxxxx";
		f.write(defaultFile.getBytes());
		f.close();
	}
	
	/**
	 * Gets the datapath for pictures
	 * @return the datapath for FlickPhoto! pictures, or "" if operation failed
	 */
	public static String getDataPath() {
		String DCIM = "";
		if(sdAvailable()) {
			File file = Environment.getExternalStorageDirectory();
			DCIM = file.getAbsolutePath() + DATAPATH;
			
			File dcim = new File(DCIM);
			
			if(!dcim.isDirectory())
				if(!createDirectory(DCIM))
					DCIM = "";
		}
		else {
			Log.e(TAG, "SD Card not available.");
		}
		
		return DCIM;
	}
	
	private static boolean createDirectory(String directory) {
		File f = new File(directory);
		return f.mkdir();
	}
		
	/**
	 * Checks if the SD card is available for use
	 * @return true if sd card is available, false otherwise
	 */
	private static boolean sdAvailable() {
		return (Environment.getExternalStorageState().
				equals(Environment.MEDIA_MOUNTED));
	}
}
